/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.arecieve.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.modules.ar.entity.Tar;
import com.jeesite.modules.ar.entity.TarDetail;
import com.jeesite.modules.ar.service.TarService;
import com.jeesite.modules.arecieve.entity.TreceivableDetail;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.fixedexpense.FixedExpense;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.entity.taccount.Taccount;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.fixedexpense.FixedExpenseService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.base.service.taccount.TaccountService;
import com.jeesite.modules.custom.service.CodeRuleService;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.pay.entity.Tpay;
import com.jeesite.modules.pay.entity.Tpayment;
import com.jeesite.modules.pay.entity.TpaymentDetail;
import com.jeesite.modules.payment.entity.Tap;
import com.jeesite.modules.payment.entity.TapDetail;
import com.jeesite.modules.prepay.entity.Tprepayment;
import com.jeesite.modules.prepay.entity.TprepaymentEstimated;
import com.jeesite.modules.prerecieve.entity.TadvancesReceived;
import com.jeesite.modules.prerecieve.entity.TadvancesReceivedEstimated;
import com.jeesite.modules.prerecieve.service.TadvancesReceivedService;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.arecieve.entity.Treceivable;
import com.jeesite.modules.arecieve.service.TreceivableService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 收款单Controller
 * @author wsm
 * @version 2021-03-22
 */
@Controller
@RequestMapping(value = "${adminPath}/arecieve/treceivable")
public class TreceivableController extends BaseController {

	@Autowired
	private TreceivableService treceivableService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private ServiceOrderService serviceOrderService;
	@Autowired
	private TarService tarService;
	@Autowired
	private CodeRuleService codeRuleService;
	@Autowired
	private TadvancesReceivedService tadvancesReceivedService;
	@Autowired
	private TaccountService taccountService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Treceivable get(String receivableId, boolean isNewRecord) {
		return treceivableService.get(receivableId, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("arecieve:treceivable:view")
	@RequestMapping(value = {"list", ""})
	public String list(Treceivable treceivable, Model model) {
		model.addAttribute("treceivable", treceivable);
        //客户
		List<Customer> customerList = customerService.findList(new Customer());
		model.addAttribute("customerList",customerList);
		//服务订单
		List<ServiceOrder> serviceOrderList = serviceOrderService.findList(new ServiceOrder());
		model.addAttribute("serviceOrderList",serviceOrderList);
		return "modules/arecieve/treceivableList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("arecieve:treceivable:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Treceivable> listData(Treceivable treceivable, HttpServletRequest request, HttpServletResponse response) {
		treceivable.setPage(new Page<>(request, response));
		Page<Treceivable> page = treceivableService.findPage(treceivable);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("arecieve:treceivable:view")
	@RequestMapping(value = "form")
	public String form(Treceivable treceivable, String arId,Model model) {

		Tar tar =new Tar();
		tar.setArId(arId);
		tar=tarService.get(tar);

		treceivable.setCustomerId(tar.getCustomerId());
		treceivable.setDate(new Date());
		treceivable.setCustomer(tar.getCustomer());

		treceivable.setServiceOrderId(tar.getServiceOrderId());

		treceivable.setCurrency(tar.getCurrency());
		//循环添加详情
		TreceivableDetail treceivableDetail =null;
		List<TreceivableDetail> treceivableDetailList =new ArrayList<>();

		for (TarDetail tarDetail : tar.getTarDetailList()) {

			treceivableDetail =new TreceivableDetail();
			treceivableDetail.setBrand(tarDetail.getBrand());
			treceivableDetail.setArea(tarDetail.getArea());
			treceivableDetail.setModel(tarDetail.getModel());
			treceivableDetail.setCarId(tarDetail.getCarId());
			treceivableDetail.setFrameNumber(tarDetail.getFrameNumber());
			treceivableDetail.setExpenseItem(tarDetail.getExpenseItem());
			treceivableDetail.setActualArAmount(tarDetail.getActualApAmount());
			treceivableDetail.setArAmount(tarDetail.getApAmount());
			treceivableDetail.setRowNumber(tarDetail.getRowNumber());
			treceivableDetail.setArCode(tar.getArCode());
			treceivableDetail.setRowNumber(tarDetail.getRowNumber());
			treceivableDetail.setActualArAmount(null);
			if(tarDetail.getActualApAmount()==null){
				treceivableDetail.setReceivedLeft(tarDetail.getApAmount()-0);
			}else{
				treceivableDetail.setReceivedLeft(tarDetail.getApAmount()-tarDetail.getActualApAmount());
			}
			treceivableDetail.setActualArAmount(null);
			treceivableDetailList.add(treceivableDetail);
		}
		treceivable.setTreceivableDetailList(treceivableDetailList);

		//银行
		Taccount taccount =new Taccount();
		taccount.setIsBank("1");
		List<Taccount> taccountList = taccountService.findList(taccount);
		model.addAttribute("taccountList",taccountList);
		//客户
		List<Customer> customerList = new ArrayList<>();
		customerList.add(treceivable.getCustomer());
		model.addAttribute("customerList",customerList);
		//服务订单
		List<ServiceOrder> serviceOrderList = new ArrayList<>();

		ServiceOrder serviceOrder = new ServiceOrder();
		serviceOrder.setServiceOrderId(treceivable.getServiceOrderId());
		serviceOrder =serviceOrderService.get(serviceOrder);
		serviceOrderList.add(serviceOrder);
		model.addAttribute("serviceOrderList",serviceOrderList);
		//应收单
		List<Tar> tarList =new ArrayList<>();
		tarList.add(tar);
		model.addAttribute("tarList",tarList);

		model.addAttribute("treceivable", treceivable);
		return "modules/arecieve/treceivableForm";
	}

	/**
	 * 查看表单详情
	 */
	@RequiresPermissions("arecieve:treceivable:view")
	@RequestMapping(value = "detail")
	public String detail(Treceivable treceivable, Model model) {
		//银行
		Taccount taccount=treceivable.getTaccount();
		List<Taccount> taccountList = new ArrayList<>();
		taccountList.add(taccount);
		model.addAttribute("taccountList",taccountList);
		//客户
		List<Customer> customerList = new ArrayList<>();
		customerList.add(treceivable.getCustomer());
		model.addAttribute("customerList",customerList);
		//服务订单
		List<ServiceOrder> serviceOrderList = new ArrayList<>();

		ServiceOrder serviceOrder = new ServiceOrder();
		serviceOrder.setServiceOrderId(treceivable.getServiceOrderId());
		serviceOrder =serviceOrderService.get(serviceOrder);
		serviceOrderList.add(serviceOrder);
		model.addAttribute("serviceOrderList",serviceOrderList);
		//应收单
		List<Tar> tarList =new ArrayList<>();
		Tar tar =new Tar();
		tar.setArCode(treceivable.getArCode());
		tar =tarService.get(tar);
		tarList.add(tar);

		model.addAttribute("treceivable", treceivable);
		return "modules/arecieve/treceivableDetail";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("arecieve:treceivable:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Treceivable treceivable) {
		//treceivableService.save(treceivable);

		if(treceivable.getIsNewRecord()){
			treceivable.setReceivableCode(codeRuleService.getCode("releasecar001"));
			treceivable.setCreateBy(UserUtils.getUser().getLoginCode());
			treceivable.setStatus1("1");
		}

		TadvancesReceived tadvancesReceived =null;
		//设置收款单应收余额
		for(int i=0;i<treceivable.getTreceivableDetailList().size();i++){
			if(treceivable.getTreceivableDetailList().get(i).getActualArAmount()!=null&&!"".equals(treceivable.getTreceivableDetailList().get(i).getActualArAmount())){
			treceivable.getTreceivableDetailList().get(i).setReceivedLeft(treceivable.getTreceivableDetailList().get(i).getArAmount()-treceivable.getTreceivableDetailList().get(i).getActualArAmount());
			treceivable.getTreceivableDetailList().get(i).setAdvancesReceivedCode(treceivable.getTreceivableDetailList().get(i).getAdvancesReceivedCode1());
			//判断有无核销
			if(treceivable.getTreceivableDetailList().get(i).getAdvancesReceivedCode()!=null&&!"".equals(treceivable.getTreceivableDetailList().get(i).getAdvancesReceivedCode())){
				tadvancesReceived =new TadvancesReceived();
				tadvancesReceived.setAdvancesReceivedCode(treceivable.getTreceivableDetailList().get(i).getAdvancesReceivedCode());
				tadvancesReceived=tadvancesReceivedService.findList(tadvancesReceived).get(0);
				tadvancesReceived =tadvancesReceivedService.get(tadvancesReceived);

				//修改预收款的金额
				for (TadvancesReceivedEstimated advancesReceivedEstimated : tadvancesReceived.getTadvancesReceivedEstimatedList()) {
					if(advancesReceivedEstimated.getRowNumber().equals(treceivable.getTreceivableDetailList().get(i).getRowNumber())&&advancesReceivedEstimated.getAdvancesReceivedType().equals(treceivable.getTreceivableDetailList().get(i).getExpenseItem())){
						//已核销金额设置
						if(advancesReceivedEstimated.getReceivedAmountActual()==null){
							advancesReceivedEstimated.setReceivedAmountActual(treceivable.getTreceivableDetailList().get(i).getActualArAmount());
						}else {
							advancesReceivedEstimated.setReceivedAmountActual(advancesReceivedEstimated.getReceivedAmountActual()+treceivable.getTreceivableDetailList().get(i).getActualArAmount());
						}
						//未核销修改
						advancesReceivedEstimated.setReceivedAmountEstimated(advancesReceivedEstimated.getReceivedSumActual()-advancesReceivedEstimated.getReceivedAmountActual());
						//预付单设置金额
						tadvancesReceived.setAdvancesReceivedBalance(tadvancesReceived.getAdvancesReceivedBalance()-treceivable.getTreceivableDetailList().get(i).getActualArAmount());
					}
				}
				//查看预收款单还有多少未报销金额,修改状态
				if(tadvancesReceived.getAdvancesReceivedBalance()==0){
					tadvancesReceived.setStatus1("4");
				}else{
					tadvancesReceived.setStatus1("3");
				}
				tadvancesReceivedService.save(tadvancesReceived);
			}
		}
		}

		Tar tar=null;
		//修改应收单
		for(int i=0;i<treceivable.getTreceivableDetailList().size();i++){
			TreceivableDetail  treceivableDetail=treceivable.getTreceivableDetailList().get(i);

			tar = new Tar();
			tar.setArCode(treceivableDetail.getArCode());
			tar =tarService.findList(tar).get(0);
			tar =tarService.get(tar);

			//设置一个布尔值判定应收单状态
			boolean b =true;
			//找到应收单下的对应应收详情
			for (TarDetail tarDetail : tar.getTarDetailList()) {
				//判断下面每个应收与实收对比
				if (tarDetail.getActualApAmount() != tarDetail.getApAmount()) {
					b = false;
				}
				if(treceivable.getTreceivableDetailList().get(i).getActualArAmount()!=null&&!"".equals(treceivable.getTreceivableDetailList().get(i).getActualArAmount())){

					if (tarDetail.getRowNumber().equals(treceivableDetail.getRowNumber())) {
						//设置回显实收
						if (tarDetail.getActualApAmount() == null) {
							tarDetail.setActualApAmount(treceivableDetail.getActualArAmount());
						} else {
							tarDetail.setActualApAmount(tarDetail.getActualApAmount() + treceivableDetail.getActualArAmount());
						}
						//设置应付余额
						tarDetail.setReiLeft(tarDetail.getApAmount() - tarDetail.getActualApAmount());
					}
				}
			}
			if(b==true){
				tar.setStatus1("4");
			}else {
				tar.setStatus1("3");
			}
			tarService.save(tar);
		}

		treceivableService.save(treceivable);
		if (treceivable.getIsNewRecord()){
			codeRuleService.updateCurrentNumber("releasecar001");
		}
		return renderResult(Global.TRUE, text("保存收款单成功！"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("arecieve:treceivable:delete")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Treceivable treceivable) {
		treceivableService.delete(treceivable);
		return renderResult(Global.TRUE, text("删除收款单成功！"));
	}
	/**
	 * 查询收款选择列表
	 * @param treceivable
	 * @param model
	 * @return
	 */
	@RequiresPermissions("arecieve:treceivable:view")
	@RequestMapping(value = {"recieveList", ""})
	public String getPaidList(Treceivable treceivable, Model model){
		//银行
		Taccount taccount =new Taccount();
		taccount.setIsBank("1");
		List<Taccount> taccountList = taccountService.findList(taccount);
		model.addAttribute("taccountList",taccountList);
		//客户
		List<Customer> customerList = customerService.findList(new Customer());
		model.addAttribute("customerList",customerList);
		//服务订单
		List<ServiceOrder> serviceOrderList = serviceOrderService.findList(new ServiceOrder());
		model.addAttribute("serviceOrderList",serviceOrderList);
		//应收单
		List<Tar> tarList = tarService.findList(new Tar());
		model.addAttribute("tarList",tarList);

		model.addAttribute("treceivable",treceivable);
		return "modules/arecieve/treceivableSelect";
	}


	/**
	 * 应收详细批量生成收款单
	 */
	@RequiresPermissions("arecieve:treceivable:view")
	@RequestMapping(value = "saveAll")
	public String saveAll(String str,String date,String customerId,String serviceOrderId,String currency,String receivableMethod,String receivableBank, Model model) {

		Treceivable treceivable =new Treceivable();
		List<TreceivableDetail> treceivableDetails =new ArrayList<>();
		//设置应收单详情
		Tar tar =null;
		if(str.length()>1){
			String[] s = str.split(",");
			TarDetail tarDetail =null;
			TreceivableDetail treceivableDetail= null;
			for(int i=0;i<s.length;i++){
				//获取应收单编号
				tarDetail=tarService.findById(s[i]);
				tar = tarService.selectOne(s[i]);

				treceivableDetail =new TreceivableDetail();
				treceivableDetail.setArCode(tar.getArCode());
				treceivableDetail.setBrand(tarDetail.getBrand());
				treceivableDetail.setArea(tarDetail.getArea());
				treceivableDetail.setModel(tarDetail.getModel());
				treceivableDetail.setCarId(tarDetail.getCarId());
				treceivableDetail.setFrameNumber(tarDetail.getFrameNumber());
				treceivableDetail.setExpenseItem(tarDetail.getExpenseItem());
				treceivableDetail.setActualArAmount(tarDetail.getActualApAmount());
				treceivableDetail.setArAmount(tarDetail.getApAmount());
				treceivableDetail.setRowNumber(tarDetail.getRowNumber());

				if(tarDetail.getActualApAmount()==null){
					treceivableDetail.setReceivedLeft(tarDetail.getApAmount());
				}else{
					treceivableDetail.setReceivedLeft(tarDetail.getApAmount()-tarDetail.getActualApAmount());
				}
				treceivableDetails.add(treceivableDetail);
			}

			//设置支收单信息
			treceivable.setTreceivableDetailList(treceivableDetails);
			treceivable .setCurrency(currency);
			treceivable .setServiceOrderId(serviceOrderId);
			treceivable.setCustomerId(customerId);
			Customer customer =new Customer();
			customer.setCustomerId(customerId);
			customer =customerService.get(customer);
			treceivable.setCustomer(customer);

			SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd");
			Date date1 = null;
			try {
				date1 = simpleDateFormat.parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			treceivable.setDate(date1);
		}


		//客户
		List<Customer> customerList = new ArrayList<>();
		customerList.add(treceivable.getCustomer());
		model.addAttribute("customerList",customerList);
		//服务订单
		List<ServiceOrder> serviceOrderList = new ArrayList<>();

		ServiceOrder serviceOrder = new ServiceOrder();
		serviceOrder.setServiceOrderId(treceivable.getServiceOrderId());
		serviceOrder =serviceOrderService.get(serviceOrder);
		serviceOrderList.add(serviceOrder);

		model.addAttribute("serviceOrderList",serviceOrderList);
		//应收单
		List<Tar> tarList =new ArrayList<>();
		//tapList.add(tap);
		model.addAttribute("tarList",tarList);

		model.addAttribute("treceivable", treceivable);
		return "modules/arecieve/treceivableForm";
	}

}